package org.example.syn;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.Timer;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Yyming
 * @version 10.0
 * Created by Yyming on 2020/9/11
 */
public class CASTest {
    Unsafe unsafe;
    private int f = 1;
    private static long aLong;

    public CASTest() throws NoSuchFieldException, IllegalAccessException {
        //通过反射获取unsafe
        Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        unsafe=(Unsafe) field.get(null);
        aLong = unsafe.objectFieldOffset(CASTest.class.getDeclaredField("f"));
    }

    private void change(){
        this.unsafe.compareAndSwapInt(this,aLong,1,0);
        System.out.println(f);
    }

    public static void main(String[] args) throws NoSuchFieldException, InterruptedException, IllegalAccessException {
        CASTest casTest = new CASTest();
        new Thread(() -> {
            while (casTest.f == 1) {
                int a = 1;
            }
            System.out.println("结束");
        }).start();

        Thread.sleep(1000);

        casTest.change();
    }
}
